<template>
    <div>
        <!-- 搜索栏 -->
        <el-card class="!border-none mb-4" shadow="never">
            <el-form class="mb-[-16px]" :model="queryParams" :inline="true">
                <el-form-item label="文档文档">
                    <div class="!w-[250px]">
                        <el-input
                            v-model="queryParams.keyword"
                            placeholder="请输入文档名称搜索"
                            clearable
                            @keyup.enter="resetPaging"
                        />
                    </div>
                </el-form-item>
                <el-form-item label="拥有者">
                    <el-input
                        v-model="queryParams.user"
                        class="!w-[250px]"
                        placeholder="请输入用户编号/昵称"
                        clearable
                        @keyup.enter="resetPaging"
                    />
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="queryParams.status" class="!w-[110px]" placeholder="全部">
                        <el-option label="全部" value="" />
                        <el-option label="待索引" value="0" />
                        <el-option label="排队中" value="1" />
                        <el-option label="索引中" value="2" />
                        <el-option label="已就绪" value="3" />
                        <el-option label="索引失败" value="4" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="resetPaging">查询</el-button>
                    <el-button @click="resetParams">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 表格栏 -->
        <el-card v-loading="pager.loading" shadow="never" class="!border-none mt-4">
            <div>
                <el-button
                    :disabled="selectData.length <= 0"
                    v-perms="['agent:know:archive:delete']"
                    @click="handleDelete(selectData)"
                    class="!mb-4"
                >
                    批量删除
                </el-button>
                <el-button
                    :disabled="selectData.length <= 0"
                    :icon="Refresh"
                    v-perms="['agent:know:archive:retry']"
                    @click="handleRetry(selectData)"
                    class="!mb-4"
                >
                    失败重试
                </el-button>
            </div>
            <el-table :data="pager.lists" size="large" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="ID" min-width="60">
                    <template #default="{ row }">
                        {{ row.id }}
                    </template>
                </el-table-column>
                <el-table-column label="拥有者" prop="user" min-width="165">
                    <template #default="{ row }">
                        <div class="flex items-center">
                            <el-avatar :size="50" :src="row?.user?.avatar" class="shrink-0" />
                            <div class="grid ml-2">
                                <p class="line-clamp-1">{{ row?.user?.nickname }}</p>
                                <el-popover
                                    :content="row?.user?.sn"
                                    effect="dark"
                                    placement="top-start"
                                >
                                    <template #reference>
                                        <p class="text-xs text-tx-placeholder line-clamp-1">
                                            {{ row?.user?.sn }}
                                        </p>
                                    </template>
                                </el-popover>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="所属知识库" prop="know" min-width="150">
                    <template #default="{ row }">
                        <el-tag type="info">{{ row?.know }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="文档名称" prop="name" min-width="150" show-tooltip-when-overflow />
                <el-table-column label="数据总量" prop="train_total" min-width="100" />
                <el-table-column label="等待学习" prop="train_waits" min-width="100" />
                <el-table-column label="状态" prop="status" min-width="100">
                    <template #default="{ row }">
                        <div v-if="row.train_mode === 'qa' && row.qa_status !== 3">
                            <el-tag v-if="row.qa_status === 0" type="info">待拆分</el-tag>
                            <el-tag v-if="row.qa_status === 1" type="primary">排队中</el-tag>
                            <el-tag v-if="row.qa_status === 2" type="warning">拆分中</el-tag>
                            <el-tooltip
                                v-if="row.qa_status === 4"
                                effect="dark"
                                placement="top-start"
                                :content="row?.fail_reason || '-'"
                            >
                                <el-tag type="danger">拆分失败</el-tag>
                            </el-tooltip>
                        </div>
                        <div v-else>
                            <el-tag v-if="row.status === 0" type="info">待索引</el-tag>
                            <el-tag v-if="row.status === 1" type="primary">排队中</el-tag>
                            <el-tag v-if="row.status === 2" type="warning">索引中</el-tag>
                            <el-tag v-if="row.status === 3" type="success">已就绪</el-tag>
                            <el-tag v-if="row.status === 4" type="danger" class="cursor-pointer">
                                <popup title="失败原因" cancelButtonText="" confirmButtonText="">
                                    <template #trigger>索引失败</template>
                                    <div class="text-error p-2">{{ row?.error || '-' }}</div>
                                </popup>
                            </el-tag>
                            <p
                                v-if="row.error"
                                class="mt-0.5 text-xs text-error line-clamp-3"
                            >
                                原因: {{ row?.error }}
                            </p>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="启用">
                    <template #default="{ row }">
                        <el-switch
                            v-model="row.is_disable"
                            :active-value="0"
                            :inactive-value="1"
                            :disabled="true"
                        />
                    </template>
                </el-table-column>
                <el-table-column label="更新时间" prop="update_time" min-width="180" />
                <el-table-column label="操作" width="160" fixed="right">
                    <template #default="{ row }">
                        <el-button
                            v-if="row.status === 4"
                            v-perms="['agent:know:archive:retry']"
                            type="warning"
                            link
                            @click="handleRetry([row.id])"
                        >
                            重试
                        </el-button>
                        <el-button
                            v-perms="['agent:know:dataset:lists']"
                            type="primary"
                            link
                            @click="handlePopup('dataset', row)"
                        >
                            查看
                        </el-button>
                        <el-button
                            v-perms="['agent:know:archive:delete']"
                            type="danger"
                            link
                            @click="handleDelete([row.id])"
                        >
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="flex justify-end mt-4">
                <paging v-model="pager" @change="queryLists" />
            </div>
        </el-card>

        <!-- 数据弹窗 -->
        <pop-data-list v-if="datasetShow" ref="datasetRef" @close="datasetShow = false" />
    </div>
</template>

<script setup lang="ts">
import { Refresh } from '@element-plus/icons-vue'
import { usePaging } from '@/hooks/usePaging'
import feedback from '@/utils/feedback'
import knowArchiveApi from '@/api/agent/know/archive'
import PopDataList from './_components/_pop_data_list.vue';

// 数据弹窗
const datasetShow = ref(false)
const datasetRef = shallowRef<InstanceType<typeof PopDataList>>()

// 查询参数
const queryParams = reactive({
    name: '',
    user: '',
    status: '',
    keyword: ''
})

// 分页查询
const { pager, queryLists, resetParams, resetPaging } = usePaging({
    fetchFun: knowArchiveApi.lists,
    params: queryParams
})

/**
 * 表格勾选
 */
const selectData = ref<number[]>([])
const handleSelectionChange = (val: any[]) => {
    selectData.value = val.map((item) => item.id)
}

/**
 * 处理删除
 *
 * @param {number[]} ids
 * @returns {Promise<void>}
 */
const handleDelete = async (ids: number[]): Promise<void> => {
    feedback.confirm('确定要删除此项数据吗?')
        .then(async () => {
            await knowArchiveApi.delete(ids)
            feedback.msgSuccess('删除成功')
            await queryLists()
        }).catch(() => {})
}

/**
 * 失败重试
 *
 * @param {number[]} ids
 * @returns {Promise<void>}
 */
const handleRetry = async (ids: number[]): Promise<void> => {
    feedback.confirm('确定要重新尝试训练吗?')
        .then(async () => {
            await knowArchiveApi.retry(ids)
            feedback.msgSuccess('操作成功')
            await queryLists()
        }).catch(() => {})
}

/**
 * 处理弹窗
 *
 * @param {string} type
 * @param {any} row
 * @returns {Promise<void>}
 */
const handlePopup = async (type: string, row?: any): Promise<void> => {
    if (type === 'dataset') {
        datasetShow.value = true
        await nextTick()
        datasetRef.value?.open(type, row)
    }
}

onMounted(async () => {
    await queryLists()
})
</script>